package com.wanm.shardingjdbc.config;

import com.alibaba.druid.pool.DruidDataSource;
import io.shardingsphere.api.config.rule.ShardingRuleConfiguration;
import io.shardingsphere.api.config.rule.TableRuleConfiguration;
import io.shardingsphere.api.config.strategy.InlineShardingStrategyConfiguration;
import io.shardingsphere.core.keygen.DefaultKeyGenerator;
import io.shardingsphere.core.keygen.KeyGenerator;
import io.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
import io.shardingsphere.shardingjdbc.util.DataSourceUtil;
import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**数据源配置
 * @author WanMing
 * @date 2019/7/21 21:57
 */
@Configuration
public class ShardingDataSourceConfig {

    /**
     * 普通的分库分表配置
     * @return
     * @throws SQLException
     */
    @Bean
    public DataSource getDataSources() throws SQLException {
        //配置表和数据源节点
        TableRuleConfiguration tableRule = new TableRuleConfiguration();
        tableRule.setLogicTable("t_user");
        tableRule.setActualDataNodes("ds${0..1}.t_user${0..1}");
        tableRule.setKeyGenerator(getGeneratedKey());

        //配置分库+分表
        tableRule.setDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("uid", "ds${uid % 2}"));
        tableRule.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("pid", "t_user${pid % 2}"));
        ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration();
        shardingRuleConfiguration.getTableRuleConfigs().add(tableRule);
        
        return ShardingDataSourceFactory.createDataSource(getDateSourceMap(), shardingRuleConfiguration, new HashMap<>(),new Properties());
    }

    public KeyGenerator getGeneratedKey(){
        KeyGenerator generatedKey = new DefaultKeyGenerator();
        return generatedKey;
    }

    /**
     * 创建多数据源 1写2读
     * @return
     */
    private Map<String,DataSource> getDateSourceMap(){
        Map<String,DataSource> dataSourceMap = new HashMap<>(3);
        for (int i = 0; i < 3; i++) {
            DruidDataSource ds0 = new DruidDataSource();
            ds0.setUsername("root");
            ds0.setPassword("root");
            ds0.setUrl("jdbc:mysql://localhost:3306/t_user"+i);
            ds0.setDriverClassName("com.mysql.jdbc.Driver");
            ds0.setMaxActive(20);
            ds0.setMinIdle(10);
            dataSourceMap.put("ds"+i, ds0);
        }
        return dataSourceMap;
    }




}
